<template>
  <button class="getCode" @click="sendCode()" ref="vcode">{{timeOut}}</button>
</template>
<script>
  import {AlertDialog} from '../../common/js/common'
  import {HttpRequest} from '../../common/js/httpFun'
  import {linklist} from '../../common/js/mockdata'
  export default({
    props: {
      'tel': {
        type: String,
        default: ''
      },
      'type': {
        type: Number,
        default: 1
      },
      'cmd': {
        type: String,
        default: 'base'
      },
      'imgVcode': {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        'timeOut': '获取验证码'
      }
    },
    methods: {
      verifyTel (tel) {
        /* 验证手机号是否正确 */
        if (!tel) {
          AlertDialog('错误', '请填写手机号')
          return false
        }
        else {
          let reg = /^(1[3|4|5|6|7|8|9])\d{9}$/
          if (!reg.test(tel)) {
            AlertDialog('错误', '请填写正确的手机号')
            return false
          }
          else {
            return true
          }
        }
      },
      sendCode () {
        let vResult = this.verifyTel(this.tel)
        if (!vResult) {
          return false
        }
        /* 调用发送验证码接口 */
        let result = HttpRequest(linklist.vcodeUrl, {
          mobile: this.tel,
          type: this.type,
          cmd: this.cmd,
          imgVcode: this.imgVcode
        }, 2)
        result.then((response) => {
          if (response.status === 200) {
            let count = 90
            this.timeOut = count + 's'
            this.$refs.vcode.setAttribute('disabled', true)
            let timeInterval = setInterval(() => {
              if (count > 0) {
                count--
                this.timeOut = count + 's'
              }
              else {
                clearInterval(timeInterval)
                this.timeOut = '获取验证码'
                this.$refs.vcode.removeAttribute('disabled')
              }
            }, 1000)
          }
        }, (response) => {
          AlertDialog('警告', '发送验证码失败，请稍后再试')
        }).catch((response) => {
          AlertDialog('警告', '发送验证码失败，请稍后再试')
        })
      }
    }
  })
</script>
